package com.agent.payment.controller;

import com.agent.common.result.ResultCode;
import com.agent.payment.service.AsiabillService;
import com.agent.payment.service.PaypalService;
import com.agent.common.entity.UserContext;
import com.agent.common.result.ApiResponse;
import com.agent.common.utils.UserContextHolder;
import com.agent.payment.entity.PaymentOrder;
import com.agent.payment.service.PaymentService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

/**
 * 支付控制器
 * @author Jeff_Wan
 * @description 处理支付相关请求，包括创建订单、支付请求、回调处理等
 */
@RestController
@RequestMapping("/payment")
@RequiredArgsConstructor
public class PaymentController {
    private final PaymentService paymentService;
    private final AsiabillService asiabillService;
    private final PaypalService paypalService;

    /**
     * 创建支付订单
     * @param planType 套餐类型
     * @param subscriptionType 订阅类型
     * @param paymentMethod 支付方式
     * @param creditConversion 积分抵扣金额
     * @return 支付订单信息
     */
    @PostMapping("/order/create")
    public ApiResponse<Object> createPaymentOrder(
            @RequestParam("planType") String planType,
            @RequestParam("subscriptionType") String subscriptionType,
            @RequestParam("paymentMethod") String paymentMethod,
            @RequestParam(name = "creditConversion", required = false) BigDecimal creditConversion) {

        // 从线程上下文中获取用户信息
        UserContext userContext = UserContextHolder.getCurrentUser();
        PaymentOrder order = paymentService.createPaymentOrder(
                userContext, planType, subscriptionType, paymentMethod, creditConversion
        );

        return ApiResponse.success(order);
    }

    /**
     * 获取支付请求参数
     * @param orderId 订单ID
     * @return 支付请求参数
     */
    @GetMapping("/request/order")
    public ApiResponse<Map<String, String>> getPaymentRequest(@RequestParam("orderId") Long orderId) {
        PaymentOrder order = paymentService.getOrderById(orderId);
        if (order == null) {
            return ApiResponse.fail(ResultCode.NOT_FOUND, "Order not found");
        }

        Map<String, String> requestParams;
        if ("ASIABILL".equalsIgnoreCase(order.getPaymentMethod())) {
            requestParams = asiabillService.createPaymentRequest(order);
            return ApiResponse.success(requestParams);
        } else if ("PAYPAL".equalsIgnoreCase(order.getPaymentMethod())) {
            String paypalUrl = paypalService.createPaymentRequest(order);
            Map<String, String> response = new HashMap<>();
            response.put("redirectUrl", paypalUrl);
            return ApiResponse.success(response);
        } else {
            return ApiResponse.fail(ResultCode.PAYMENT_GATEWAY_ERROR, "Unsupported payment method");
        }
    }

    /**
     * 处理支付回调
     * @param paymentMethod 支付方式
     * @param callbackData 回调数据
     * @param signature 签名
     * @return 处理结果
     */
    @PostMapping("/callback/{paymentMethod}")
    public ApiResponse<String> handlePaymentCallback(
            @PathVariable("paymentMethod") String paymentMethod,
            @RequestBody String callbackData,
            @RequestHeader("X-Signature") String signature) {

        boolean success = paymentService.handlePaymentCallback(paymentMethod, callbackData, signature);
        if (success) {
            return ApiResponse.success("Callback processed successfully");
        } else {
            return ApiResponse.fail(ResultCode.PAYMENT_GATEWAY_ERROR, "Callback processing failed");
        }
    }

    /**
     * 查询订单状态
     * @param orderId 订单ID
     * @return 订单状态
     */
    @GetMapping("/status/order")
    public ApiResponse<PaymentOrder> getOrderStatus(@RequestParam("orderId") Long orderId) {
        PaymentOrder order = paymentService.getOrderById(orderId);
        if (order == null) {
            return ApiResponse.fail(ResultCode.NOT_FOUND, "Order not found");
        }
        return ApiResponse.success(order);
    }
}